var ZMQPlugin= function() {};
ZMQPlugin.prototype.receiveMessage = {}

ZMQPlugin.prototype.error_callback = function(msg) {
  console.log("Javascript Callback Error: " + JSON.stringify(msg));
}

ZMQPlugin.prototype.call_native = function(name, args, callback) {
  var ret = cordova.exec(callback, this.error_callback, "ZMQPlugin", name, args);
  return ret;
}

// 链接
ZMQPlugin.prototype.connect = function(args, callback) {
  var data = [args];
  this.call_native('zmqConnect', data, callback);
}

// 发送
ZMQPlugin.prototype.send = function(args, callback) {
  var data = [args];
  this.call_native('zmqSendToPeer', data, callback);
}

// 接收
ZMQPlugin.prototype.receivemessage = function(callback) {
  var data = [];
  this.call_native('zmqRecvFromPeer', data, callback);
  try {
    data = JSON.stringify(data);
    var bToObj = JSON.parse(data);
    this.receiveMessage = bToObj
    console.log("window.plugins.ZMQPlugin.receiveMessage", bToObj);
    cordova.fireDocumentEvent('zmq.messages', bToObj);
  } catch(exception) {
    console.log("zmqPlugin:pushCallback " + exception);
  }
}

ZMQPlugin.prototype.getDeviceToken = function(callback) {
  var data = [];
  this.call_native('getDeviceToken', data, callback);
}

//接收事件
ZMQPlugin.prototype.receiveMessage = function(data) {
  try {
      console.log("window.plugins.ZMQPlugin:receiveMessage");
      data = JSON.stringify(data);
      var bToObj = JSON.parse(data);
      this.receiveMessage = bToObj
      cordova.fireDocumentEvent('zmq.messages', null);
  } catch(exception) {
      console.log("zmqPlugin:pushCallback " + exception);
  }
}

// 断开
ZMQPlugin.prototype.disConnect = function(arg0, callback) {
  var data = [arg0];
  this.call_native('zmqDisConnect', data, callback);
}

if(!window.plugins) {
  window.plugins = {};
}

if(!window.plugins.ZMQPlugin) {
  window.plugins.ZMQPlugin = new ZMQPlugin();
}
module.exports = new ZMQPlugin();